<template>
	<el-dialog v-model="dialogVisible" :title="title" width="500px" draggable @close="closeDialog">
		<NewForm :formOptions="props.handleFormOptions" :searchForm="handleForm" :showFooter="false"
			ref="handleFormRef" />
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="closeDialog">取消</el-button>
				<el-button type="primary" @click="confirmDialog">
					确定
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>


<script lang="ts" setup name="HandleModal">
import { ref, reactive, watch } from 'vue';
import type { PropType } from "vue";
import NewForm from 'src/components/NewForm/index.vue'
import { HandleType } from 'src/pages/clueManager/const';
import utils from 'src/utils';
const handleFormRef = ref<any>();
const props = defineProps({
	defaultData: {
		type: Object,
		default: {}
	},
	editData: {
		type: Object,
		default: {}
	},
	handleFormOptions: {
		type: Array as PropType<FormOptions[]>,
		required: true
	},
	handleType: {
		type: String,
		default: 'ADD'
	},
	title: String,
	requestParams: {
		type: Object,
		default: {}
	},
	requestFunc: Function,
	callbackFunc: Function
})
const handleForm = reactive<SearchFormType>({})
const dialogVisible = ref(false);
const openDialog = () => {
	dialogVisible.value = true;
};
const closeDialog = () => {
	dialogVisible.value = false;
	clearCache();
};
watch(props, () => {
	let defaultData = { ...props.defaultData }
	if (props.handleType === HandleType.EIDT) {
		defaultData = { ...defaultData, ...props.editData }
	}
	Object.keys(defaultData).forEach(key => {
		handleForm[key] = `${defaultData[key]}`
	})
})
const submit = (formData: any) => {
	if (!props.requestFunc) return
	props.requestFunc({ ...formData, ...(props.requestParams || {}) }).then((res: any) => {
		utils.commonNotification({
			condition: `${res.code}` === '0',
			msg_success: '操作成功',
			callback_success: () => { props.callbackFunc && props.callbackFunc() }
		})
	});
}
const confirmDialog = async () => {
	const valid = await handleFormRef.value?.validateForm()
	if (valid) {
		const copyHandleForm = utils.cloneDeep(handleForm)
		if (copyHandleForm.new_pw && copyHandleForm.new_pw_repeat) {
			if (copyHandleForm.new_pw !== copyHandleForm.new_pw_repeat) {
				utils.commonNotification({
					condition: false,
					msg_failed: '两次输入的密码不一致',
				})
				return
			} else {
				delete copyHandleForm.new_pw_repeat
			}
		}
		submit(copyHandleForm)
	}
}
const clearCache = () => {
	handleFormRef.value?.clearCache();
	Object.keys(handleForm).forEach(key => {
		if (handleForm[key]) delete handleForm[key]
	})
}

defineExpose({ openDialog, closeDialog });
</script>

<style scoped lang="scss">
.dialog-footer {
	display: flex;
	justify-content: center;
	align-items: center;
}
</style>